# 导入包
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
import pymysql
import warnings
warnings.filterwarnings('ignore') # 忽略错误
plt.rcParams['font.family']='SimHei'
plt.rcParams['axes.unicode_minus']=False # 使中文字体正常显示

# 导入数据
data = pd.read_csv(r'E:\Lagou\阶段7\模块二作业\ab_data.csv')
print(data.head(5))
# 计算统计量
# 均值
df = data.groupby(['group','landing_page'],as_index=False)['converted'].mean()
print(df)
mean_diff = df.converted[2]-df.converted[1]
print(mean_diff)
# 标准差
df1 = data.groupby(['group','landing_page'],as_index=False)['converted'].count()
n1=df1.converted[1]
n2=df1.converted[2]
print(n1,n2)
sigma = np.sqrt(df.converted[2]*(1-df.converted[2])/n1 + df.converted[1]*(1-df.converted[1])/n1)
print(sigma)
# 统计量P值
statistics_P = 1-stats.norm.cdf(mean_diff,0,sigma)
if statistics_P>0.05:
    print("实验组点击率小于等于对照组")
else:
    print("实验组点击率高于对照组")
#封装函数
def abtest_p(df: pd.DataFrame, alpha=0.05, group_col: str = None, value_col: str = None):
    '''
    :param df: 被分析DateFrame对象
    :param alpha:临界值
    :param group_col: 组列的名字，默认为df的第1列
    :param value_col:值列的名字,默认为df的第2列
    :return:statistics,p_value,p_type
    '''
    # 列名
    if not group_col:
        group_col = df.columns[0]
    if not value_col:
        value_col = df.columns[1]
    group_mean = df.groupby(group_col,as_index=False).mean()
    m1=group_mean.iloc[0,1]
    m2=group_mean.iloc[1,1]
    mean_diff = m2-m1
    group_n = df.groupby(group_col,as_index=False).count()
    sigma = np.sqrt(m1*(1-m1)/group_n.iloc[0,1] + m2*(1-m2)/group_n.iloc[1,1])
    p_value_left = stats.norm.cdf(mean_diff,0,sigma)
    r1 ="显著" if p_value_left<alpha else "不显著"
    p_value_right = 1-stats.norm.cdf(mean_diff,0,sigma)
    r2 = "显著" if p_value_right < alpha else "不显著"
    p_value_2 = 2*stats.norm.cdf(mean_diff,0,sigma)
    r3 = "显著" if p_value_2 < alpha else "不显著"
    content =[
        [group_mean.iloc[0,0],group_mean.iloc[1,0],mean_diff,"左侧检验",p_value_left,r1],
        [group_mean.iloc[0,0],group_mean.iloc[1,0],mean_diff,"右侧检验", p_value_right, r2],
        [group_mean.iloc[0, 0], group_mean.iloc[1, 0], mean_diff, "双侧检验", p_value_2, r3]
    ]
    result = pd.DataFrame(content,columns=["p1","p2","Statistics","method","p_value","conclusion"])

    return result

df2 = data.loc[((data.group=="control")&(data.landing_page=="old_page"))|((data.group=="treatment")&(data.landing_page=="new_page")),
               ["group","converted"]]
print(df2.head())
print(abtest_p(df2))
